package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.MemberContext;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDTO;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.ReservationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;


/**
 * 预约信息Service业务层处理
 *
 * @author bear_tianyu
 * @date 2025-02-27
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private IFamilyMemberService familyMemberService;

    //状态为2(取消)
    private static final Integer CANCELLED_STATUS = 2;

    //待报道状态
    private static final Integer TREAT_STATUS = 0;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        Long id = MemberContext.get();
        reservation.setUpdateBy(String.valueOf(id));
        return reservationMapper.selectReservationList(reservation);
    }


    /**
     * 新增预约信息
     *
     * @param reservationDTO 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(ReservationDTO reservationDTO) {
        //先查询当前预约时间预约次数是否已满
        int count = this.lambdaQuery()
                .eq(Reservation::getTime, reservationDTO.getTime())
//                .list().size();
                .count().intValue();
        if (count >= 6) {
            throw new BaseException("请换个时间点吧,这个时间点已经预约满了哦");
        }
        //新建家属对象
        Reservation reservation = new Reservation();
        BeanUtils.copyProperties(reservationDTO, reservation);
        reservation.setTime(LocalDateTime.now());
        reservation.setStatus(TREAT_STATUS);
        Long id = MemberContext.get();
        reservation.setUpdateBy(String.valueOf(id));
        reservation.setCreateTime(DateTime.now());
        reservation.setUpdateTime(DateTime.now());
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param id 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Long id) {
        //从线程局部变量获取当前登录人的id
        Long userId = MemberContext.get();
        //先去查询当前登录次数是否已经超过最大预约次数
        int count = cancelledCount();
        if (count >= 3) {
            throw new BaseException("不能在修改了哦，你的修改次数已经到达上限了");
        }
        try {
            this.lambdaUpdate()
                    .eq(Reservation::getId, id)
                    .eq(Reservation::getUpdateBy, userId)
                    .set(Reservation::getStatus, CANCELLED_STATUS);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 查询当天取消预约数量
     *
     * @return
     */
    @Override
    public int cancelledCount() {
        //获取当天的开始时间和结束时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        //从线程局部变量获取当前登录人的id
        Long id = MemberContext.get();
        //从数据库查询数据集，更新时间在当天时间范围和状态为取消
        int count = this.lambdaQuery()
                .eq(Reservation::getUpdateBy, id)
                .eq(Reservation::getStatus, CANCELLED_STATUS)
                .between(Reservation::getUpdateTime, startTime, endTime)
                .list().size();
        //放回取消次数
        return count;
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<ReservationVO> countByTime(String time) {
        List<ReservationVO> reservationVOList = reservationMapper.countByTime(time);
        return reservationVOList;
    }

}
